package com.sxp.dao.impl;

import com.sxp.dao.UserDao;
import com.sxp.bean.User;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;

import java.util.List;

/**
 * @author 宋晓盼
 * @since 2019/5/7 12:45
 */
public class UserDaoImpl implements UserDao {
    private SessionFactory factory = new Configuration().configure().buildSessionFactory();

    @Override
    public void adduser(User user) {

    }

    @Override
    public String selectuser(String username) {
        return null;
    }

    @Override
    public int addbuycar(int id) {
        return 0;
    }

    @Override
    public User getByUsername(String username) {
        List result = null;
        try(Session session = factory.openSession()) {
            String hql = "from User as user where user.username = :username";
            Query query = session.createQuery(hql);
            query.setParameter("username", username);
            result = query.list();
        } catch (HibernateException e) {
            e.printStackTrace();
        }
        if (result != null && result.size() == 1) {
            return (User) result.get(0);
        } else {
            return null;
        }
    }

    @Override
    public Integer save(User user) {
        Transaction transaction = null;
        Integer userId = null;
        try (Session session = factory.openSession()) {

            transaction = session.beginTransaction();
            userId = (Integer) session.save(user);
            transaction.commit();
        } catch (HibernateException e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
        return userId;
    }

    @Override
    public void update(User user) {

        Transaction transaction = null;
        try (Session session = factory.openSession()) {
            transaction = session.beginTransaction();
            session.update(user);
            transaction.commit();
        } catch (HibernateException e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }
}
